using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using FileNamingConfig = DocumentCreationSystem.Models.FileNamingConfig;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 文件命名规则配置对话框
    /// </summary>
    public partial class FileNamingConfigDialog : Window
    {
        private readonly ILogger<FileNamingConfigDialog> _logger;
        private readonly IFileNamingService _fileNamingService;
        private readonly IServiceProvider _serviceProvider;
        private FileNamingConfig _currentConfig;

        public bool IsApplied { get; private set; } = false;

        public FileNamingConfigDialog(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
            _logger = serviceProvider.GetRequiredService<ILogger<FileNamingConfigDialog>>();
            _fileNamingService = serviceProvider.GetRequiredService<IFileNamingService>();

            InitializeComponent();
            LoadCurrentConfig();
            SetupEventHandlers();
        }

        /// <summary>
        /// 加载当前配置
        /// </summary>
        private void LoadCurrentConfig()
        {
            try
            {
                _currentConfig = _fileNamingService.GetCurrentConfig();
                
                // 设置UI控件的值
                ChapterNamingTemplateTextBox.Text = _currentConfig.ChapterNamingTemplate;
                OutlineNamingTemplateTextBox.Text = _currentConfig.OutlineNamingTemplate;
                CharacterNamingTemplateTextBox.Text = _currentConfig.CharacterNamingTemplate;
                TimelineNamingTemplateTextBox.Text = _currentConfig.TimelineNamingTemplate;
                
                AutoSanitizeFileNamesCheckBox.IsChecked = _currentConfig.AutoSanitizeFileNames;
                UseChineseNumbersCheckBox.IsChecked = _currentConfig.UseChineseNumbers;
                
                // 设置默认文件扩展名
                foreach (ComboBoxItem item in DefaultFileExtensionComboBox.Items)
                {
                    if (item.Content.ToString() == _currentConfig.DefaultFileExtension)
                    {
                        DefaultFileExtensionComboBox.SelectedItem = item;
                        break;
                    }
                }

                UpdatePreviews();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载文件命名配置失败");
                MessageBox.Show("加载配置失败，将使用默认配置", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                LoadDefaultConfig();
            }
        }

        /// <summary>
        /// 加载默认配置
        /// </summary>
        private void LoadDefaultConfig()
        {
            _currentConfig = new FileNamingConfig();
            
            ChapterNamingTemplateTextBox.Text = _currentConfig.ChapterNamingTemplate;
            OutlineNamingTemplateTextBox.Text = _currentConfig.OutlineNamingTemplate;
            CharacterNamingTemplateTextBox.Text = _currentConfig.CharacterNamingTemplate;
            TimelineNamingTemplateTextBox.Text = _currentConfig.TimelineNamingTemplate;
            
            AutoSanitizeFileNamesCheckBox.IsChecked = _currentConfig.AutoSanitizeFileNames;
            UseChineseNumbersCheckBox.IsChecked = _currentConfig.UseChineseNumbers;
            DefaultFileExtensionComboBox.SelectedIndex = 0; // .txt
            
            UpdatePreviews();
        }

        /// <summary>
        /// 设置事件处理器
        /// </summary>
        private void SetupEventHandlers()
        {
            // 文本框变化时更新预览
            ChapterNamingTemplateTextBox.TextChanged += (s, e) => UpdatePreviews();
            OutlineNamingTemplateTextBox.TextChanged += (s, e) => UpdatePreviews();
            CharacterNamingTemplateTextBox.TextChanged += (s, e) => UpdatePreviews();
            TimelineNamingTemplateTextBox.TextChanged += (s, e) => UpdatePreviews();
            
            // 复选框变化时更新预览
            AutoSanitizeFileNamesCheckBox.Checked += (s, e) => UpdatePreviews();
            AutoSanitizeFileNamesCheckBox.Unchecked += (s, e) => UpdatePreviews();
            UseChineseNumbersCheckBox.Checked += (s, e) => UpdatePreviews();
            UseChineseNumbersCheckBox.Unchecked += (s, e) => UpdatePreviews();
            
            // 下拉框变化时更新预览
            DefaultFileExtensionComboBox.SelectionChanged += (s, e) => UpdatePreviews();
        }

        /// <summary>
        /// 更新预览
        /// </summary>
        private void UpdatePreviews()
        {
            try
            {
                var config = GetConfigFromUI();
                
                // 示例数据
                var bookTitle = "我的小说";
                var volumeNumber = 1;
                var volumeName = "修炼之路";
                var chapterNumber = 1;
                var chapterTitle = "初入修仙界";
                var characterName = "李逍遥";
                var outlineType = "全书";

                // 更新预览文本
                ChapterPreviewText.Text = $"示例：{_fileNamingService.GenerateChapterFileName(bookTitle, volumeNumber, volumeName, chapterNumber, chapterTitle, config.DefaultFileExtension, config)}";
                OutlinePreviewText.Text = $"示例：{_fileNamingService.GenerateOutlineFileName(bookTitle, outlineType, config.DefaultFileExtension, config)}";
                CharacterPreviewText.Text = $"示例：{_fileNamingService.GenerateCharacterFileName(bookTitle, characterName, config.DefaultFileExtension, config)}";
                TimelinePreviewText.Text = $"示例：{_fileNamingService.GenerateTimelineFileName(bookTitle, volumeNumber, config.DefaultFileExtension, config)}";
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "更新预览失败");
            }
        }

        /// <summary>
        /// 从UI获取配置
        /// </summary>
        private FileNamingConfig GetConfigFromUI()
        {
            return new FileNamingConfig
            {
                ChapterNamingTemplate = ChapterNamingTemplateTextBox.Text,
                OutlineNamingTemplate = OutlineNamingTemplateTextBox.Text,
                CharacterNamingTemplate = CharacterNamingTemplateTextBox.Text,
                TimelineNamingTemplate = TimelineNamingTemplateTextBox.Text,
                AutoSanitizeFileNames = AutoSanitizeFileNamesCheckBox.IsChecked ?? true,
                UseChineseNumbers = UseChineseNumbersCheckBox.IsChecked ?? false,
                DefaultFileExtension = (DefaultFileExtensionComboBox.SelectedItem as ComboBoxItem)?.Content.ToString() ?? ".txt"
            };
        }

        /// <summary>
        /// 章节模板帮助
        /// </summary>
        private void ChapterTemplateHelp_Click(object sender, RoutedEventArgs e)
        {
            var helpText = @"章节文件命名可用变量：

{BookTitle} - 书籍标题
{VolumeNumber} - 卷号（数字）
{VolumeNumber:D2} - 卷号（两位数字，如01）
{VolumeName} - 卷名称
{ChapterNumber} - 章节号（数字）
{ChapterNumber:D3} - 章节号（三位数字，如001）
{ChapterTitle} - 章节标题
{Date} - 当前日期（yyyy-MM-dd）
{Time} - 当前时间（HH-mm-ss）

示例模板：
{BookTitle}_第{VolumeNumber:D2}卷_{VolumeName}_第{ChapterNumber:D3}章_{ChapterTitle}";

            MessageBox.Show(helpText, "章节命名模板帮助", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 大纲模板帮助
        /// </summary>
        private void OutlineTemplateHelp_Click(object sender, RoutedEventArgs e)
        {
            var helpText = @"大纲文件命名可用变量：

{BookTitle} - 书籍标题
{OutlineType} - 大纲类型（如：全书、分卷、章节）
{VolumeNumber} - 卷号（仅分卷大纲）
{VolumeNumber:D2} - 卷号（两位数字）
{Date} - 当前日期（yyyy-MM-dd）

示例模板：
{BookTitle}_{OutlineType}_大纲
{BookTitle}_第{VolumeNumber:D2}卷_大纲";

            MessageBox.Show(helpText, "大纲命名模板帮助", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 角色模板帮助
        /// </summary>
        private void CharacterTemplateHelp_Click(object sender, RoutedEventArgs e)
        {
            var helpText = @"角色设定文件命名可用变量：

{BookTitle} - 书籍标题
{CharacterName} - 角色名称
{CharacterType} - 角色类型（如：主角、配角、反派）
{Date} - 当前日期（yyyy-MM-dd）

示例模板：
{BookTitle}_角色_{CharacterName}
{BookTitle}_{CharacterType}_{CharacterName}";

            MessageBox.Show(helpText, "角色命名模板帮助", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 时间线模板帮助
        /// </summary>
        private void TimelineTemplateHelp_Click(object sender, RoutedEventArgs e)
        {
            var helpText = @"时间线文件命名可用变量：

{BookTitle} - 书籍标题
{VolumeNumber} - 卷号（可选）
{VolumeNumber:D2} - 卷号（两位数字）
{TimelineType} - 时间线类型（如：主线、支线）
{Date} - 当前日期（yyyy-MM-dd）

示例模板：
{BookTitle}_时间线
{BookTitle}_时间线_第{VolumeNumber:D2}卷
{BookTitle}_{TimelineType}_时间线";

            MessageBox.Show(helpText, "时间线命名模板帮助", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 恢复默认设置
        /// </summary>
        private void ResetToDefault_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("确定要恢复默认设置吗？这将清除所有自定义配置。", 
                "确认恢复默认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            
            if (result == MessageBoxResult.Yes)
            {
                LoadDefaultConfig();
            }
        }

        /// <summary>
        /// 预览效果
        /// </summary>
        private void Preview_Click(object sender, RoutedEventArgs e)
        {
            UpdatePreviews();
            MessageBox.Show("预览已更新，请查看各个模板下方的示例效果。", "预览", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var config = GetConfigFromUI();
                
                // 验证配置
                if (string.IsNullOrWhiteSpace(config.ChapterNamingTemplate))
                {
                    MessageBox.Show("章节命名模板不能为空", "验证失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 保存配置
                _fileNamingService.SaveConfig(config);
                
                IsApplied = true;
                DialogResult = true;
                
                MessageBox.Show("文件命名配置已保存", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存文件命名配置失败");
                MessageBox.Show($"保存配置失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
